package com.smartwheel.web.controller;

import com.sw.model.Point;
import com.sw.render.TileRender;
import com.sw.render.png.PngTileRender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/tiles")
public class TilesController {

    private static final Logger LOG = LoggerFactory.getLogger(TilesController.class);

    private TileRender tileRender = new PngTileRender();

    @RequestMapping("/{zoom}/{x}/{y}")
    public void renderTile(@PathVariable Integer zoom, @PathVariable Integer x, @PathVariable Integer y, HttpServletResponse response) {
        LOG.warn("Zoom =[" + zoom + "], x=[" + x + "], y=[" + y + "]");


        response.setContentType("image/png");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            tileRender.renderTile(new Point("dragos1", (double) x, (double) y, 10D, 10D), outputStream);
        } catch (Exception ex) {
            LOG.error("Some problem occurred when rendering tile.", ex);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (Exception ex) {
                    // ignored
                }
            }
        }
    }
}
